<template>
  <el-drawer v-model="visiable" :title="dynamicTitle" size="90%" :before-close="onBeforeClose" class="drawer">
    <!-- id: string;
  courseId: string;
  courseName: string;
  courseCode: string;
  studentId: string;
  stuName: string;
  stuClass: string;
  major: string;
  college: string;
  grade: string;
  workId: string;
  tchName: string;
  score: number | string;
  createTime: string; -->
    <div id="content">
      <globle-linear-border>
        <el-card class="searchBox">
          <el-form :inline="true">
            <el-form-item label="学号">
              <el-input v-model="pageQuery.otherParams.studentId" placeholder="输入学生学号搜索" clearable />
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="pageQuery.otherParams.stuName" placeholder="输入学生姓名搜索" clearable />
            </el-form-item>
            <el-form-item label="学院">
              <el-input v-model="pageQuery.otherParams.college" placeholder="输入学生学院搜索" clearable />
            </el-form-item>
            <el-form-item label="专业">
              <el-input v-model="pageQuery.otherParams.major" placeholder="输入学生专业搜索" clearable />
            </el-form-item>
            <el-form-item label="班级">
              <el-input v-model="pageQuery.otherParams.stuClass" placeholder="输入学生班级搜索" clearable />
            </el-form-item>
            <el-form-item>
              <section>
                <el-button type="primary" icon="Search" @click.stop="getPageInfo">搜 索</el-button>
                <el-button type="warning" icon="RefreshRight" @click.stop="reset">重 置</el-button>
                <el-button v-if="!isEdit" type="success" icon="Edit" @click.stop="onEdit">编 辑</el-button>
                <el-button v-if="isEdit" type="danger" icon="Check" @click.stop="onEdit">退出编辑</el-button>
                <el-button v-if="isEdit" type="success" icon="Check" @click.stop="onSave">保 存</el-button>
                <!-- <el-button type="warning" icon="Upload" @click="onExpose">导出数据</el-button> -->
              </section>
            </el-form-item>
          </el-form>
        </el-card>
      </globle-linear-border>
      <!-- 表格 -->
      <globle-linear-border style="margin-top: 20px">
        <el-card class="mainBox">
          <span v-if="tableData.rows">
            <el-form :model="tableData" ref="formRef">
              <el-table :border="true" stripe ref="tableRef" :data="tableData.rows" cell-class-name="table-cell"
                header-cell-class-name="table-header-cell" empty-text="暂无选择该课程的学生">
                <el-table-column label="年级">
                  <template #default="scope">{{ scope.row.grade + '级' }}</template>
                </el-table-column>
                <el-table-column property="studentId" label="学号" show-overflow-tooltip />
                <el-table-column property="stuName" label="姓名" />
                <el-table-column property="college" label="学院" />
                <el-table-column property="major" label="专业" />
                <el-table-column property="stuClass" label="班级">
                  <template #default="scope">{{ scope.row.stuClass }}</template>
                </el-table-column>
                <el-table-column property="score" label="分数" width="220">
                  <template #default="scope">
                    <span v-if="!isEdit">{{ scope.row.score ? scope.row.score : '暂未录入' }}</span>
                    <el-form-item v-else :prop="`rows[${scope.$index}].score`" :rules="scoreRule">
                      <el-input v-model="scope.row.score" placeholder="请输入成绩" />
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <el-pagination v-model:currentPage="pageQuery.pageParams.pageNum"
              v-model:page-size="pageQuery.pageParams.pageSize" :page-sizes="pageSizeOption" :background="true"
              :small="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.totalSize"
              @size-change="onSizeChange" @current-change="onCurrentChange" />
          </span>
        </el-card>
      </globle-linear-border>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { APIData, ICourse, IScorePageParams, IPageRes, IScore, IScoreParams, Score } from '../../../../type';
import { useAPI } from '../../../../request/api';
import { useUserStore } from '../../../../store/user';
import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
import { useRuleUtils } from '../../../../utils/validate';

const formRef = ref();
const ruleUtils = useRuleUtils();
const rowData = ref({} as ICourse)
// let rowData = {} as ICourse;
const isEdit = ref(false)
const visiable = ref(false); //add batchAdd update
const api = useAPI();
const userstore = useUserStore();
const pageSizeOption = [5, 10, 15, 20];
const tableData = ref({} as IPageRes);
const tableRef = ref<InstanceType<typeof ElTable>>();
// const formData = ref();
const pageQuery = reactive<IScorePageParams>({
  otherParams: {
    courseId: '',
    studentId: '',
    stuName: '',
    stuClass: '',
    major: '',
    college: '',
    grade: '',
    workId: '',
    score: '',
  },
  pageParams: {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: '',
  },
});

const scoreRule = [{ validator: ruleUtils.score, trigger: 'blur' }]
// const scoreRule =  { validator: ruleUtils.integer, trigger: 'blur' }

const dynamicTitle = computed(() => {
  if (rowData.value) return `${rowData.value.teachClass}成绩录入`
  else return `成绩录入`
})

const open = async (row: ICourse) => {
  rowData.value = row;
  visiable.value = true;
  reset();
};

const reset = () => {
  pageQuery.otherParams = {
    courseId: rowData.value.id,
    studentId: '',
    stuName: '',
    stuClass: '',
    major: '',
    college: '',
    grade: '',
    workId: userstore.userInfo.workId,
    score: '',
  }
  pageQuery.pageParams = {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: '',
  }
  getPageInfo();
  // pageQuery.otherParams = {
  //   createTime: '',
  //   student: { 
  //     studentId: '',
  //     name: '',
  //     sex: '',
  //     stuClass: '',
  //     college: '',
  //     major: ''
  //    },
  //    teacher: { workId:userstore.userInfo.workId },
  //   course: { courseId: rowData.value.id } 
  // }
  // getPageInfo();
}

const onEdit = () => {
  isEdit.value = !isEdit.value;
}

const onSave =  () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const updateList = [] as Score[];
      const addList = [] as Score[];
      tableData.value.rows.forEach((item: IScore) => {
        if (item.id) {
          updateList.push({
            id: item.id,
            courseId: rowData.value.id,
            score: item.score,
            studentId: item.studentId,
            workId: userstore.userInfo.workId,
          })
        } else {
          addList.push({
            courseId: rowData.value.id,
            score: item.score,
            studentId: item.studentId,
            workId: userstore.userInfo.workId,
          })
        }
      })
      // console.log('updateList',updateList);
      // console.log('addList',addList);
      const postData: IScoreParams = { addList, updateList }
      const res: APIData = await api.score.save(postData);
      if (res.data) {
        isEdit.value = false;
        ElMessage.success('保存成功');
      }
      // console.log('res',res);
    }else return false;
  })
}

const onBeforeClose = (done: () => void) => {
  if (isEdit.value) {
    ElMessageBox.confirm('您还未保存，在关闭前需要保存吗?', {
      confirmButtonText: '保存',
      cancelButtonText: '放弃保存',
      type: 'warning',
    }).then(() => {
        onSave();
      }).catch(() => {
        uninstall();
        done();
      })
  }else done();
}

const uninstall = () => {
  formRef.value.clearValidate();
  isEdit.value = false;
}

// //导出
// const onExpose = () => {
//   window.open(`${api.baseUrl}/teacher/fileExport/stuInfo?stage=${pageQuery.otherParams.stage}&workId=${store.userInfo.workId}`, '_self');
// };

//分页大小
const onSizeChange = (val: number) => {
  pageQuery.pageParams.pageSize = val;
  pageQuery.pageParams.pageNum = 1;
  getPageInfo();
};


//分页页码
const onCurrentChange = (val: number) => {
  pageQuery.pageParams.pageNum = val;
  getPageInfo();
};

const getPageInfo = async () => {
  const res: APIData = await api.score.findPage(pageQuery);
  if (res.code == 200) tableData.value = res.data;
};

defineExpose({ open });
</script>

<style lang="scss" scoped>
#content {
  height: 100%;
  padding: 14px 32px;
  overflow: auto;

  .searchBox {
    &-item {
      margin-right: 10px;
    }

    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
    }

    section {
      display: flex;
    }

    :deep(.el-input__wrapper) {
      width: 200px;
    }
  }

  .mainBox {
    :deep(.el-checkbox__inner) {
      background-color: var(--main-color);
      transition: background 0.3s ease;
    }

    :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: var(--active-color);
      transition: background 0.3s ease;
    }

    .el-form-item {
      margin-bottom: 0;
    }

    :deep(.el-form-item__error) {
      position: absolute;
      right: 8px;
      top: 8px;
      left: auto;
    }
  }
}
</style>
